package com.biostime.qdingding.modules.qd.service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.biostime.qdingding.common.utils.StringUtils;
import com.biostime.qdingding.modules.qd.dao.CourseOrderDao;
import com.biostime.qdingding.modules.qd.entity.Contract;
import com.biostime.qdingding.modules.qd.entity.Course;
import com.biostime.qdingding.modules.qd.entity.CourseOrder;
import com.biostime.qdingding.modules.qd.entity.Courseprice;
import com.biostime.qdingding.modules.qd.entity.Promotemplate;
import com.biostime.qdingding.modules.qd.entity.Promotion;
import com.biostime.qdingding.modules.qd.promotions.MemberDiscountor;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author chenweicheng
 * 课程价格，优惠前后价格
 * @version 2015-12-08
 */
@Service
@Transactional(readOnly = true)
public class PriceService {
	
	
	@Autowired
	private CourseOrderDao courseOrderDao;
	
	@Autowired
	private PromotionService promotionService;
	
	@Autowired
	private ContractService contractService;
	
	//设置价格的保留小数点的位数
	public final static int priceSize = 1;
	
	/**
	 * 获取优惠前的价格列表，闲时忙时
	 * @param price
	 * @return
	 */
	@SuppressWarnings({ "unused", "deprecation", "unchecked", "rawtypes" })
	public List<Courseprice> getPriceList(String price) throws JsonParseException, JsonMappingException, IOException{
		List<Courseprice> priceList =null;
		ObjectMapper mapper = new ObjectMapper();
		List list=mapper.readValue(price, List.class);
		JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, Courseprice.class);  
		priceList=  (List<Courseprice>)mapper.readValue(price, javaType); 
		return  priceList;
	} 
	
	
	/**
	 * 获取优惠前，优惠后的价格
	 * @param course
	 * @return
	 * @throws Exception
	 */
	public HashMap<String,Object> getPriceMap(Course course,String studentId) throws Exception{

		//课程预约人数
		int num=courseOrderDao.apiCourseBook(String.valueOf(course.getId()), String.valueOf(course.getType()));	

		//获取该学员的订单
		CourseOrder course2 = courseOrderDao.apiGetByStuAndCourse(course.getId(), studentId,String.valueOf(course.getType()));		
		if(course2 != null){
			if(course2.getState().equals("ordered") || course2.getState().equals("signed")){
				num -= 1;
			}else{
				if(course.getCapacity() <= num){
					num = course.getCapacity() -1 ;
				}
			}
		}else{
			if(course.getCapacity() <= num){
				num = course.getCapacity() -1 ;
			}
		}

		//判断价格类型，闲时或者忙时
		List<Courseprice> priceList = getPriceList(course.getPrice());		
		double moneyFreeze = 0;
		double moneyBefore = 0;
		
		//当前闲时优惠id
		int freeDiscountId = 0;
		int priceType = course.getPriceType();
		
		for(int j=0;j<priceList.size();j++){
			if(priceType == 0){
				moneyBefore = priceList.get(j).getPrice();
				moneyFreeze = moneyBefore;
			}else{
				int starton = priceList.get(j).getStarton();
				int endon = priceList.get(j).getEndon();	
				if(priceList.get(j).getPrice() > moneyFreeze){
					moneyFreeze = priceList.get(j).getPrice();
				}
				if(num < endon && num+1 >= starton){
					moneyBefore = priceList.get(j).getPrice();
					freeDiscountId = Integer.valueOf(priceList.get(j).getId());
				}	
			}
		}
					
		//获取优惠列表
		List<HashMap<String,Object>>  promotionIdMap = null;	
		List<Promotion> promotionList = new ArrayList<Promotion>();
		promotionIdMap = promotionService.apiGetIdByStudent(studentId);
		if(promotionIdMap != null){
			Promotion promotion = null;
			for(int i=0;i<promotionIdMap.size();i++){
				if(promotionIdMap.get(i).get("PROMOTIONID") !=null ){
					BigDecimal id =  (BigDecimal) promotionIdMap.get(i).get("PROMOTIONID");
					promotion = promotionService.apiGetById(String.valueOf(id));
					promotionList.add(promotion);
				} 
			}					
		}
	
		//设置优惠后价格
		course.setPriceNow(moneyBefore);
		course.setStudentId(Integer.parseInt(studentId));
		
		//设置优惠
		for(int i=0;i<promotionList.size();i++){
			Promotemplate template = new Promotemplate();
			template.setFormula((String)promotionIdMap.get(i).get("FORMULA"));
			Promotion promotion=promotionList.get(i);
			promotion.setTemplate(template);
			course.addPromotion(promotion); 
		}
		
		//打折
		course.discount();	

		//第一步：获取合同额
		Promotion promotion = course.getPromotions().get(MemberDiscountor.Formula);
		Contract contract = contractService.getByStudentId(course.getStudentId());
		
		//第二步：根据合同额确定折扣
		double discount = 10.0d;
		if(contract!=null){
			ObjectMapper mapper = new ObjectMapper();
			List<MemberDiscountor.Arg> args = null;
			try {
				args = Arrays.asList(mapper.readValue(promotion.getArgValue(), MemberDiscountor.Arg[].class));
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
			if(args != null && args.size()>0){
				for(MemberDiscountor.Arg arg : args){
					double level = StringUtils.toDouble(arg.getLevel());
					if(level == contract.getAmount()){
						discount = arg.getDiscount();
					}
				}
			}
		}	

		//打折后的priceTypeList
		if(priceList != null && !priceList.isEmpty()){
			for(int i=0;i<priceList.size();i++){
				priceList.get(i).setPrice(changeMoney(priceList.get(i).getPrice() * (discount/(double)10))); 
			}
			//去掉第一个档次
			if(priceType ==1)
				priceList.remove(0);
		}
		
		HashMap<String,Object> map = new HashMap<String,Object>();
		
		//优惠前价格
		map.put("moneyBefore", changeMoney(moneyBefore));	
		
		//优惠后价格
		map.put("moneyAfter", changeMoney(course.getPriceNow()));
		
		//冻结金额		
		map.put("moneyFreeze", changeMoney(moneyFreeze));
		
		//会员折扣
		map.put("discount", discount);
		
		//促销列表
		map.put("promotionList",promotionList);
		
		//闲时优惠价格列表
		map.put("priceList", priceList);
		
		//当前闲时优惠id
		map.put("freeDiscountId", freeDiscountId);
				
		return map;
	}
		
	/**此方法用于设置double类型数据的小数位
	 * 注意的是，不保留0小数位
	 * @param money
	 * @return
	 */
	public double changeMoney(double money){ 
		BigDecimal b = new BigDecimal(money);  
		double changeAfter = b.setScale(priceSize,BigDecimal.ROUND_HALF_UP).doubleValue();  
		return changeAfter;
	}
}

